package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.mapper.SysRoleUserMapper;
import com.atguigu.spzx.manager.service.SysRoleUserService;
import com.atguigu.spzx.model.dto.system.AssginRoleDto;
import com.atguigu.spzx.model.entity.system.SysRoleUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysRoleUserServiceImpl extends ServiceImpl<SysRoleUserMapper, SysRoleUser> implements SysRoleUserService {

    @Resource
    private SysRoleUserMapper sysRoleUserMapper;

    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        Long userId = assginRoleDto.getUserId();
        List<Long> roleIdList = assginRoleDto.getRoleIdList();

//        LambdaUpdateWrapper<SysRoleUser> wrapper = new LambdaUpdateWrapper<SysRoleUser>().in(SysRoleUser::getUserId, userId);
//        baseMapper.delete(wrapper);

        sysRoleUserMapper.deleteByUserId(userId);

        if(CollectionUtils.isEmpty(roleIdList)){
            throw new GuiguException(ResultCodeEnum.NO_ROLE_ID_LIST);
        }
//        List<SysRoleUser> roleUserList = new ArrayList<>();
//        for (Long roleId : roleIdList) {
//            SysRoleUser roleUser = new SysRoleUser();
//            roleUser.setUserId(userId);
//            roleUser.setRoleId(roleId);
//            roleUserList.add(roleUser);
//        }
//        this.saveBatch(roleUserList);

        List<SysRoleUser> roleUserList = roleIdList.stream().map(roleId -> {
            SysRoleUser sysRoleUser = new SysRoleUser();
            sysRoleUser.setUserId(userId);
            sysRoleUser.setRoleId(roleId);
            return sysRoleUser;
        }).collect(Collectors.toList());
        this.saveBatch(roleUserList);
    }
}
